#include "stdafx.h"
#include "Thread.h"
#include <process.h>


CThread::CThread()
{
	m_hThread = NULL;
	m_nThreadID = 0;
	m_ThreadParam.pEntry = NULL;
	m_ThreadParam.pParam = NULL;
}


CThread::~CThread()
{
	if(m_hThread)
	{
		CloseHandle(m_hThread);
	}
}

bool CThread::Start(PTHREADENTRY pFunc, LPVOID pParam, int nPriority)
{
	if(!IsClosed())
	{
		return false;
	}

	if(m_hThread)
	{
		CloseHandle(m_hThread);
		m_hThread = NULL;
		m_nThreadID = 0;
	}

	m_ThreadParam.pEntry = pFunc;
	m_ThreadParam.pParam = pParam;

	unsigned int initFlag = 0;
	if(nPriority != THREAD_PRIORITY_NORMAL)
	{
		initFlag = CREATE_SUSPENDED;
	}

	int ret = _beginthreadex(NULL, 0, BaseThreadEntry, &m_ThreadParam, initFlag, &m_nThreadID);

	if(ret > 0)
	{
		m_hThread = (HANDLE)ret;

		if(nPriority != THREAD_PRIORITY_NORMAL)
		{
			SetThreadPriority(m_hThread, nPriority);
			ResumeThread(m_hThread);
		}

		return true;
	}
	else
	{
		return false;
	}

}

bool CThread::Suspend()
{
	return (SuspendThread(m_hThread) != 0xffffffff);
}

bool CThread::Resume()
{
	return (ResumeThread(m_hThread) != 0xffffffff);
}

void CThread::Terminate(DWORD dwExitCode)
{
	TerminateThread(m_hThread, dwExitCode);
}

unsigned __stdcall CThread::BaseThreadEntry(LPVOID pParam)
{
	_ThreadParam *pThreadParam = (_ThreadParam *) pParam;

	DWORD dwRet = pThreadParam->pEntry(pThreadParam->pParam);

	return (unsigned)dwRet;
}

